package cn.exrick.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.exrick.pojo.TbOrderReturnExchange;
import cn.exrick.service.OrderReturnExchangeService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;

import cn.exrick.common.exception.XmallException;
import cn.exrick.common.jedis.JedisClient;
import cn.exrick.mapper.TbMemberMapper;
import cn.exrick.mapper.TbOrderItemMapper;
import cn.exrick.mapper.TbOrderMapper;
import cn.exrick.mapper.TbOrderShippingMapper;
import cn.exrick.pojo.TbAddress;
import cn.exrick.pojo.TbMember;
import cn.exrick.pojo.TbOrder;
import cn.exrick.pojo.TbOrderExample;
import cn.exrick.pojo.TbOrderItem;
import cn.exrick.pojo.TbOrderItemExample;
import cn.exrick.pojo.TbOrderShipping;
import cn.exrick.pojo.TbPreferential;
import cn.exrick.pojo.TbPreferentialItem;
import cn.exrick.pojo.dto.CreateOrderRequest;
import cn.exrick.pojo.dto.ItemDto;
import cn.exrick.pojo.front.CartProduct;
import cn.exrick.pojo.front.Order;
import cn.exrick.service.AddressService;
import cn.exrick.service.ItemService;
import cn.exrick.service.OrderFrontService;
import cn.exrick.service.PreferentialItemService;
import cn.exrick.service.PreferentialService;
import cn.exrick.utils.EmailUtil;
import cn.exrick.utils.IDUtil;
import cn.exrick.utils.mybatis.Page;
import cn.exrick.utils.mybatis.PageParam;

/**
 * @author Exrickx
 */
@Service
public class OrderFrontServiceImpl implements OrderFrontService {

	private final static Logger log = LoggerFactory.getLogger(OrderFrontServiceImpl.class);

	@Autowired
	private TbMemberMapper tbMemberMapper;
	@Autowired
	private TbOrderMapper tbOrderMapper;
	@Autowired
	private TbOrderItemMapper tbOrderItemMapper;
	@Autowired
	private TbOrderShippingMapper tbOrderShippingMapper;
	@Autowired
	private ItemService itemService;
	@Autowired
	private JedisClient jedisClient;

	@Autowired
	private PreferentialService preferentialService;
	@Autowired
	private PreferentialItemService preferentialItemService;

	@Autowired
	private AddressService addressService;
	@Autowired
	private OrderReturnExchangeService orderReturnExchangeService;

	@Value("${CART_PRE}")
	private String CART_PRE;
	@Value("${EMAIL_SENDER}")
	private String EMAIL_SENDER;
	@Value("${PAY_EXPIRE}")
	private int PAY_EXPIRE;
	@Value("${SERVER_URL}")
	private String SERVER_URL;
	@Value("${qrnum}")
	private Integer QRNUM;

	@Autowired
	private EmailUtil emailUtil;

	@Override
	public Page<Order> getOrderList(Long userId, int page, int size, Integer status) {

		// 分页
		if (page <= 0) {
			page = 1;
		}
		PageHelper.startPage(page, size);
		PageParam pageParam = new PageParam(page - 1, size);
		Page<Order> pageOrder = new Page<Order>(pageParam);
		List<Order> list = new ArrayList<>();

		TbOrderExample example = new TbOrderExample();
		TbOrderExample.Criteria criteria = example.createCriteria();
		criteria.andUserIdEqualTo(userId);
		if (status != null) {
			if(status.equals(new Integer(6))){
				// 2:已发货(待收货),3:已收货(交易成功,待评价),4:已评价 可申请售后
				List<Integer> statusList = new ArrayList<>();
				statusList.add(2);
				statusList.add(3);
				statusList.add(4);
				criteria.andStatusIn(statusList);
			}else{
				criteria.andStatusEqualTo(status);
			}
		}
		example.setOrderByClause("create_time DESC");
		List<TbOrder> listOrder = tbOrderMapper.selectByExample(example);
		for (TbOrder tbOrder : listOrder) {

			judgeOrder(tbOrder);

			Order order = new Order();
			// orderId
			order.setOrderId(Long.valueOf(tbOrder.getOrderId()));
			// orderStatus
			order.setOrderStatus(tbOrder.getStatus());
			// createDate
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			order.setCreateDate(tbOrder.getCreateTime());
			order.setUpdateDate(tbOrder.getUpdateTime());
			// address
			TbOrderShipping tbOrderShipping = tbOrderShippingMapper.selectByPrimaryKey(tbOrder.getOrderId());
			TbAddress address = new TbAddress();
			address.setUserName(tbOrderShipping.getReceiverName());
			address.setStreetName(tbOrderShipping.getReceiverAddress());
			address.setTel(tbOrderShipping.getReceiverPhone());
			order.setAddressInfo(address);
			order.setShippingCode(tbOrder.getShippingCode());
			order.setShippingName(tbOrder.getShippingName());
			// orderTotal
			if (tbOrder.getPayment() == null) {
				order.setOrderTotal(new BigDecimal(0));
			} else {
				order.setOrderTotal(tbOrder.getPayment());
			}
			// goodsList
			TbOrderItemExample exampleItem = new TbOrderItemExample();
			TbOrderItemExample.Criteria criteriaItem = exampleItem.createCriteria();
			criteriaItem.andOrderIdEqualTo(tbOrder.getOrderId());
			List<TbOrderItem> listItem = tbOrderItemMapper.selectByExample(exampleItem);
			List<CartProduct> listProduct = new ArrayList<>();
			for (TbOrderItem tbOrderItem : listItem) {
				CartProduct cartProduct = new CartProduct();
				cartProduct.setProductId(Long.valueOf(tbOrderItem.getItemId()));
				cartProduct.setProductName(tbOrderItem.getTitle());
				cartProduct.setSalePrice(tbOrderItem.getPrice());
				cartProduct.setProductNum(Long.valueOf(tbOrderItem.getNum()));
				cartProduct.setProductImg(tbOrderItem.getPicPath());

				listProduct.add(cartProduct);
			}
			order.setGoodsList(listProduct);

			// returnExchangeStatus
			if(order.getOrderStatus() == 2 || order.getOrderStatus() ==3 || order.getOrderStatus() == 4){
				TbOrderReturnExchange orderReturnExchange = orderReturnExchangeService.getByOrderId(String.valueOf(order.getOrderId()));
				if(null != orderReturnExchange){
					order.setReturnExchangeStatus(orderReturnExchange.getStatus());
				}else{
					// -1 待申请售后
					order.setReturnExchangeStatus(-1);
				}
			}
			list.add(order);
		}
		PageInfo<Order> pageInfo = new PageInfo<>(list);
		pageOrder.setTotalCount(getMemberOrderCount(userId, status));
		pageOrder.setResult(list);
		return pageOrder;
	}

	@Override
	public Order getOrder(Long orderId) {

		Order order = new Order();

		TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(String.valueOf(orderId));
		if (tbOrder == null) {
			throw new XmallException("通过id获取订单失败");
		}

		Date validTime = judgeOrder(tbOrder);
		if (validTime != null) {
			order.setFinishDate(validTime);
		}
		order.setShippingCode(tbOrder.getShippingCode());
		order.setShippingName(tbOrder.getShippingName());
		order.setMemberId(tbOrder.getUserId());
		// orderId
		order.setOrderId(Long.valueOf(tbOrder.getOrderId()));
		// orderStatus
		order.setOrderStatus(tbOrder.getStatus());
		// createDate
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		order.setCreateDate(tbOrder.getCreateTime());
		order.setUpdateDate(tbOrder.getUpdateTime());
		// payDate
		if (tbOrder.getPaymentTime() != null) {
			order.setPayDate(tbOrder.getPaymentTime());
		}
		// closeDate
		if (tbOrder.getCloseTime() != null) {
			String closeDate = formatter.format(tbOrder.getCloseTime());
			order.setCloseDate(tbOrder.getCloseTime());
		}
		// finishDate
		if (tbOrder.getEndTime() != null && tbOrder.getStatus() == 4) {
			order.setFinishDate(tbOrder.getEndTime());
		}
		// consignTime
		if (tbOrder.getConsignTime() != null) {
			order.setConsignTime(tbOrder.getConsignTime());
		}
		// address
		TbOrderShipping tbOrderShipping = tbOrderShippingMapper.selectByPrimaryKey(tbOrder.getOrderId());
		TbAddress address = new TbAddress();
		address.setUserName(tbOrderShipping.getReceiverName());
		address.setStreetName(tbOrderShipping.getReceiverAddress());
		address.setTel(tbOrderShipping.getReceiverPhone());
		order.setAddressInfo(address);
		order.setShippingCode(tbOrder.getShippingCode());
		order.setShippingName(tbOrder.getShippingName());
		// orderTotal
		if (tbOrder.getPayment() == null) {
			order.setOrderTotal(new BigDecimal(0));
		} else {
			order.setOrderTotal(tbOrder.getPayment());
		}
		// goodsList
		TbOrderItemExample exampleItem = new TbOrderItemExample();
		TbOrderItemExample.Criteria criteriaItem = exampleItem.createCriteria();
		criteriaItem.andOrderIdEqualTo(tbOrder.getOrderId());
		List<TbOrderItem> listItem = tbOrderItemMapper.selectByExample(exampleItem);
		List<CartProduct> listProduct = new ArrayList<>();
		for (TbOrderItem tbOrderItem : listItem) {
			CartProduct cartProduct = new CartProduct();
			cartProduct.setProductId(Long.valueOf(tbOrderItem.getItemId()));
			cartProduct.setProductName(tbOrderItem.getTitle());
			cartProduct.setSalePrice(tbOrderItem.getPrice());
			cartProduct.setProductNum(Long.valueOf(tbOrderItem.getNum()));
			cartProduct.setProductImg(tbOrderItem.getPicPath());

			listProduct.add(cartProduct);
		}
		order.setGoodsList(listProduct);

		// returnExchangeStatus
		if(order.getOrderStatus() == 2 || order.getOrderStatus() ==3 || order.getOrderStatus() == 4){
			TbOrderReturnExchange orderReturnExchange = orderReturnExchangeService.getByOrderId(String.valueOf(order.getOrderId()));
			if(null != orderReturnExchange){
				order.setReturnExchangeStatus(orderReturnExchange.getStatus());
			}else{
				// -1 待申请售后
				order.setReturnExchangeStatus(-1);
			}
		}

		return order;
	}

	@Override
	public int cancelOrder(Long orderId) {
		TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(String.valueOf(orderId));
		if (tbOrder == null) {
			throw new XmallException("通过id获取订单失败");
		}
		tbOrder.setStatus(5);
		tbOrder.setCloseTime(new Date());
		if (tbOrderMapper.updateByPrimaryKey(tbOrder) != 1) {
			throw new XmallException("取消订单失败");
		}
		TbOrderItemExample example = new TbOrderItemExample();
		TbOrderItemExample.Criteria criteria = example.createCriteria();
		criteria.andOrderIdEqualTo(String.valueOf(orderId));
		List<TbOrderItem> list = tbOrderItemMapper.selectByExample(example);
		for (TbOrderItem orderItem : list) {
			ItemDto itemDto = itemService.getItemById(Long.parseLong(orderItem.getItemId()));
			if (itemDto != null) {
				itemDto.setNum(itemDto.getNum() == null ? 01 : (itemDto.getNum() + 1));
				itemService.updateItem(itemDto.getId(), itemDto);
			}
		}
		return 1;
	}

	@Override
	public Long createOrder(CreateOrderRequest request) {
		TbAddress address = addressService.getAddress(request.getAddressId());
		Long memberId = request.getMemberId();
		if (address == null || !address.getUserId().equals(memberId)) {
			throw new XmallException("地址不存在");
		}
		TbMember member = tbMemberMapper.selectByPrimaryKey(memberId);
		if (member == null) {
			throw new XmallException("获取下单用户失败");
		}

		TbOrder order = new TbOrder();
		// 生成订单ID
		Long orderId = IDUtil.getRandomId();
		order.setOrderId(String.valueOf(orderId));
		order.setUserId(memberId);
		order.setBuyerNick(member.getUsername());
		order.setCreateTime(new Date());
		order.setUpdateTime(new Date());
		// 0:未付款,1:已付款(未发货),2:已发货(待收货),3:已收货(交易成功,待评价),4:已评价,5:交易关闭
		order.setStatus(0);
		order.setBuyerMessage(request.getBuyerMessage());
		order.setExpressType(request.getExpressType());
		if (tbOrderMapper.insert(order) != 1) {
			throw new XmallException("生成订单失败");
		}

		BigDecimal payment = new BigDecimal(0);

		List<CartProduct> list = request.getCartProductList();
		for (CartProduct cartProduct : list) {
			ItemDto itemDto = itemService.getItemById(cartProduct.getProductId());
			if (itemDto == null) {
				throw new XmallException("商品不存在");
			}
			if (itemDto.getLimitNum() != null && itemDto.getLimitNum() > 0
					&& itemDto.getLimitNum() < cartProduct.getProductNum()) {
				throw new XmallException(itemDto.getTitle() + "限购" + itemDto.getLimitNum() + "件");
			}
			if (itemDto.getNum() == null || itemDto.getNum() <= 0 || itemDto.getNum() < cartProduct.getProductNum()) {
				throw new XmallException(itemDto.getTitle() + "库存不足");
			}
			itemDto.setNum(itemDto.getNum() - 1);
			itemService.updateItem(itemDto.getId(), itemDto);

			TbOrderItem orderItem = new TbOrderItem();
			// 生成订单商品ID
			Long orderItemId = IDUtil.getRandomId();
			orderItem.setId(String.valueOf(orderItemId));
			orderItem.setItemId(String.valueOf(itemDto.getId()));
			orderItem.setOrderId(String.valueOf(orderId));
			orderItem.setNum(Math.toIntExact(cartProduct.getProductNum()));
			orderItem.setPrice(itemDto.getPrice());
			orderItem.setOriginal(itemDto.getOriginal());
			orderItem.setTitle(itemDto.getTitle());
			orderItem.setPicPath(cartProduct.getProductImg());
			orderItem.setTotalFee(itemDto.getPrice().multiply(BigDecimal.valueOf(cartProduct.getProductNum())));

			// 所有的优惠方案,一个个比较
			List<TbPreferentialItem> preferentialItems = preferentialItemService
					.findByItemId(cartProduct.getProductId(), TbPreferentialItem.STATUS_ABLE);
			if (preferentialItems != null && preferentialItems.size() > 0) {
				double total = 0;
				for (TbPreferentialItem preferentialItem : preferentialItems) {
					TbPreferential preferential = preferentialService.findById(preferentialItem.getPreferentialId());
					if (preferential == null) {
						continue;
					}
					boolean flag = false;
					if (preferential.getMoney().doubleValue() > 0) {// 有对总价进行限制
						if (preferential.getMoney().compareTo(orderItem.getTotalFee()) <= 0) {
							flag = true;
						} else {
							flag = false;
						}
					}
					if (preferential.getNum().doubleValue() > 0) {// 有对总数量进行限制
						if (preferential.getNum() <= orderItem.getNum()) {
							flag = true;
						} else {
							flag = false;
						}
					}
					if (flag) {
						if (preferential.getPrice() != null) {
							orderItem.setPrice(orderItem.getPrice().subtract(preferential.getPrice()));
							orderItem.setTotalFee(orderItem.getPrice().multiply(new BigDecimal(orderItem.getNum())));
						}
						if (preferential.getTotal() != null) {
							total += preferential.getTotal().doubleValue();
						}
					}
				}
				orderItem.setTotalFee(orderItem.getTotalFee().subtract(new BigDecimal(total)));
			}
			payment = payment.add(orderItem.getTotalFee());

			if (tbOrderItemMapper.insert(orderItem) != 1) {
				throw new XmallException("生成订单商品失败");
			}

			// 删除购物车中含该订单的商品
			try {
				List<String> jsonList = jedisClient.hvals(CART_PRE + ":" + memberId);
				for (String json : jsonList) {
					CartProduct cart = new Gson().fromJson(json, CartProduct.class);
					if (cart.getProductId().equals(cartProduct.getProductId())) {
						jedisClient.hdel(CART_PRE + ":" + memberId, cart.getProductId() + "");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// 重新设置总价
		order.setPayment(payment);
		tbOrderMapper.updateByPrimaryKey(order);

		// 物流表
		TbOrderShipping orderShipping = new TbOrderShipping();
		orderShipping.setOrderId(String.valueOf(orderId));
		orderShipping.setReceiverName(address.getUserName());
		orderShipping.setReceiverAddress(address.getStreetName());
		orderShipping.setReceiverPhone(address.getTel());
		orderShipping.setCreated(new Date());
		orderShipping.setUpdated(new Date());

		if (tbOrderShippingMapper.insert(orderShipping) != 1) {
			throw new XmallException("生成物流信息失败");
		}

		return orderId;
	}

	@Override
	public int delOrder(Long orderId) {
		TbOrder order = tbOrderMapper.selectByPrimaryKey(String.valueOf(orderId));
		if (order.getStatus() != 0 && order.getStatus() != 4 && order.getStatus() != 5) {
			throw new XmallException("订单不允许删除");
		}
		if (tbOrderMapper.deleteByPrimaryKey(String.valueOf(orderId)) != 1) {
			throw new XmallException("删除订单失败");
		}

		TbOrderItemExample example = new TbOrderItemExample();
		TbOrderItemExample.Criteria criteria = example.createCriteria();
		criteria.andOrderIdEqualTo(String.valueOf(orderId));
		List<TbOrderItem> list = tbOrderItemMapper.selectByExample(example);
		for (TbOrderItem tbOrderItem : list) {
			if (tbOrderItemMapper.deleteByPrimaryKey(tbOrderItem.getId()) != 1) {
				throw new XmallException("删除订单商品失败");
			}
		}

		if (tbOrderShippingMapper.deleteByPrimaryKey(String.valueOf(orderId)) != 1) {
			throw new XmallException("删除物流失败");
		}
		return 1;
	}

//    @Override
//    public String payOrder(TbThanks tbThanks) {
//
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String time = sdf.format(new Date());
//        tbThanks.setTime(time);
//        tbThanks.setState(0);
//        tbThanks.setDate(new Date());
//        TbMember tbMember = tbMemberMapper.selectByPrimaryKey(Long.valueOf(tbThanks.getUserId()));
//        if (tbMember != null) {
//            tbThanks.setUsername(tbMember.getUsername());
//        }
//        if (tbThanksMapper.insert(tbThanks) != 1) {
//            throw new XmallException("保存捐赠支付数据失败");
//        }
//
//        //设置订单为已付款
//        TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(tbThanks.getOrderId());
//        tbOrder.setStatus(1);
//        tbOrder.setUpdateTime(new Date());
//        tbOrder.setPaymentTime(new Date());
//        if (tbOrderMapper.updateByPrimaryKey(tbOrder) != 1) {
//            throw new XmallException("更新订单失败");
//        }
//        //发送通知确认邮件
//        String tokenName = UUID.randomUUID().toString();
//        String token = UUID.randomUUID().toString();
//        if (tbThanks.getCustom() != null && tbThanks.getCustom()) {
//            //自定义金额生成四位数随机标识
//            Random random = new Random();
//            int end2 = random.nextInt(9999);
//            //如果不足两位前面补0
//            String str = String.format("%04d", end2);
//            tbThanks.setPayNum(str);
//        } else {
//            // 从redis中取出num
//            String key = "XMALL_XPAY_NUM_" + tbThanks.getPayType();
//            String value = jedisClient.get(key);
//            // 初始化
//            if (StringUtils.isBlank(value)) {
//                jedisClient.set(key, "0");
//            }
//            // 取出num
//            String num = String.valueOf(Integer.parseInt(jedisClient.get(key)) + 1);
//            if (QRNUM.equals(Integer.valueOf(num))) {
//                jedisClient.set(key, "0");
//            } else {
//                // 更新记录num
//                jedisClient.set(key, String.valueOf(num));
//            }
//            tbThanks.setPayNum(num);
//        }
//        //设置验证token键值对 tokenName:token
//        jedisClient.set(tokenName, token);
//        jedisClient.expire(tokenName, PAY_EXPIRE);
//        tbThanks = getAdminUrl(tbThanks, String.valueOf(tbThanks.getId()), tokenName, token);
//        emailUtil.sendTemplateEmail(EMAIL_SENDER, "【XMall商城】待审核处理", "email-admin", tbThanks);
//        return tbThanks.getPayNum();
//    }

	@Override
	public int passPay(String tokenName, String token, String id, String sendType) {

		// 验证token
		if (StringUtils.isBlank(tokenName) || StringUtils.isBlank(tokenName) || StringUtils.isBlank(id)) {
			return -1;
		}
		String value = jedisClient.get(tokenName);
		if (!value.equals(token)) {
			return -1;
		}
		// 修改订单状态
		TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(id);
		if (tbOrder != null) {
			tbOrder.setStatus(4);
			tbOrder.setEndTime(new Date());
			tbOrder.setUpdateTime(new Date());
			if (tbOrderMapper.updateByPrimaryKey(tbOrder) != 1) {
				return 0;
			}
		}
//        //发送通知邮箱
//        if (StringUtils.isNotBlank(tbThanks.getEmail()) && EmailUtil.checkEmail(tbThanks.getEmail())) {
//            tbThanks.setTime(DateUtil.formatTime(tbThanks.getDate()));
//            if ("0".equals(sendType)) {
//                emailUtil.sendTemplateEmail(EMAIL_SENDER, "【XMall商城】支付成功通知", "pay-success", tbThanks);
//            } else if ("1".equals(sendType)) {
//                emailUtil.sendTemplateEmail(EMAIL_SENDER, "【XMall商城】支付成功通知", "senddep", tbThanks);
//            }
//        }
		return 1;
	}

	@Override
	public int backPay(String tokenName, String token, String id) {

		// 验证token
		if (StringUtils.isBlank(tokenName) || StringUtils.isBlank(tokenName) || StringUtils.isBlank(id)) {
			return -1;
		}
		String value = jedisClient.get(tokenName);
		if (!value.equals(token)) {
			return -1;
		}
		// 修改订单状态
		TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(id);
		if (tbOrder != null) {
			tbOrder.setStatus(6);
			tbOrder.setCloseTime(new Date());
			tbOrder.setUpdateTime(new Date());
			if (tbOrderMapper.updateByPrimaryKey(tbOrder) != 1) {
				return 0;
			}
		}
//        //发送通知邮箱
//        if (StringUtils.isNotBlank(tbThanks.getEmail()) && EmailUtil.checkEmail(tbThanks.getEmail())) {
//            tbThanks.setTime(DateUtil.formatTime(tbThanks.getDate()));
//            emailUtil.sendTemplateEmail(EMAIL_SENDER, "【XMall商城】支付失败通知", "pay-fail", tbThanks);
//        }
		return 1;
	}

	@Override
	public int notShowPay(String tokenName, String token, String id) {

		// 验证token
		if (StringUtils.isBlank(tokenName) || StringUtils.isBlank(tokenName) || StringUtils.isBlank(id)) {
			return -1;
		}
		String value = jedisClient.get(tokenName);
		if (!value.equals(token)) {
			return -1;
		}
		// 修改订单状态
		TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(id);
		if (tbOrder != null) {
			tbOrder.setStatus(4);
			tbOrder.setEndTime(new Date());
			tbOrder.setUpdateTime(new Date());
			if (tbOrderMapper.updateByPrimaryKey(tbOrder) != 1) {
				return 0;
			}
		}
//        //发送通知邮箱
//        if (StringUtils.isNotBlank(tbThanks.getEmail()) && EmailUtil.checkEmail(tbThanks.getEmail())) {
//            tbThanks.setTime(DateUtil.formatTime(tbThanks.getDate()));
//            emailUtil.sendTemplateEmail(EMAIL_SENDER, "【XMall商城】支付失败通知", "pay-notshow", tbThanks);
//        }
		return 1;
	}

	@Override
	public int payDel(String tokenName, String token, String id) {

		// 验证token
		if (StringUtils.isBlank(tokenName) || StringUtils.isBlank(tokenName) || StringUtils.isBlank(id)) {
			return -1;
		}
		String value = jedisClient.get(tokenName);
		if (!value.equals(token)) {
			return -1;
		}
		// 修改订单状态
		TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(id);
		if (tbOrder != null) {
			tbOrder.setStatus(6);
			tbOrder.setCloseTime(new Date());
			tbOrder.setUpdateTime(new Date());
			if (tbOrderMapper.updateByPrimaryKey(tbOrder) != 1) {
				return 0;
			}
		}
//        //发送通知邮箱
//        if (StringUtils.isNotBlank(tbThanks.getEmail()) && EmailUtil.checkEmail(tbThanks.getEmail())) {
//            tbThanks.setTime(DateUtil.formatTime(tbThanks.getDate()));
//            emailUtil.sendTemplateEmail(EMAIL_SENDER, "【XMall商城】支付失败通知", "pay-fail", tbThanks);
//        }
		return 1;
	}

	/**
	 * 判断订单是否超时未支付
	 */
	public Date judgeOrder(TbOrder tbOrder) {

		Date result = null;
		if (tbOrder.getStatus() == 0) {
			// 判断是否已超1天
			long diff = System.currentTimeMillis() - tbOrder.getCreateTime().getTime();
			long days = diff / (1000 * 60 * 60 * 24);
			if (days >= 1) {
				// 设置失效
				tbOrder.setStatus(5);
				tbOrder.setCloseTime(new Date());
				if (tbOrderMapper.updateByPrimaryKey(tbOrder) != 1) {
					throw new XmallException("更新订单失效失败");
				}
			} else {
				// 返回到期时间
				long time = tbOrder.getCreateTime().getTime() + 1000 * 60 * 60 * 24;
				result = new Date(time);
			}
		}
		return result;
	}

	public int getMemberOrderCount(Long userId, Integer status) {

		TbOrderExample example = new TbOrderExample();
		TbOrderExample.Criteria criteria = example.createCriteria();
		criteria.andUserIdEqualTo(userId);
		if (status != null) {
			criteria.andStatusEqualTo(status);
		}
		List<TbOrder> listOrder = tbOrderMapper.selectByExample(example);
		if (listOrder != null) {
			return listOrder.size();
		}
		return 0;
	}
}
